<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: luchao@clcw.com.cn                                             |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\Other;

use AuctionCore\System\AuctionException;

/**
 * 运营平台 
 * @author      luchao
 */
class Raffle
{


    // private $raffle_type = '';
    // public function __construct($type)
    // {
    //     $this->raffle_type = $type;
    // }

    /**
     * 添加活动
     */
    public function add($sets)
    {
        $data = array();
        $data['a_name'] = $sets['a_name'];
        $data['amount'] = $sets['amount'];
        $data['emp_id'] = $sets['emp_id'];
        $data['type'] = $sets['type'];
        $data['starttime'] = $sets['start_date'];
        $data['endtime'] = $sets['end_date'];
        $data['createtime'] = date('Y-m-d H:i:s');
        $data['denomination'] = $sets['denomination'];
        $data['branch_id'] = $sets['bc_city'];
        $data['form'] = $sets['form'];
        $data['coupon_end_date'] = $sets['coupon_end_date'];
        //开启事务
        M()->startTrans();

        $id = M('activity')->add($data);

        M('activity')->where("aid='" . $id . "'")->save(array('activity_no' => $id + 100000000));

        if ($data['type'] == 2) {
            $type_name ='(活动)'.$data['a_name'];
            $ct_id = M('coupon_type')->add(array('type_name' => $type_name, 'branch_company' => $data['branch_id'], 'a_id'=> $id));
        }
        if ($id < 1 || ($data['type'] == 2 && $ct_id < 1)) {
            M()->rollback();
            return false;
        }
        M()->commit();
       
        return $id;
    }
    /**
     * 获取指定活动信息
     * @return   Array
     */
    public function search_one($aid)
    {
        return M('activity')->where("aid=".$aid)->find();
    }

    /**
     * 修改指定活动信息
     * @return  
     */
    public function update_one($eidt,$aid){
         M()->startTrans();
       //修改活动表
        $ok = M('activity')->where("aid=".$aid)->save($eidt);

        //修改代金券类型表
        if ($eidt['type'] == 2) {

            $ok1 = M('coupon_type')->where("a_id=".$aid)->save(array('type_name'=>'(活动)'.$eidt['a_name'], 'branch_company' => $eidt['branch_id']));
        }
        
        //出错回滚
        // if ($ok < 1 || ($ok1 < 1 && $eidt['type'] == 2)) {
        if ($ok < 1) {
            M()->rollback();

            return false;
        }
        M()->commit();

        return $ok;
    }

    /**
     * 给指定的订单绑定卡券
     * @return  array
     */
    public function order_binding_card($order_id,$type){
        $nowdate = date("Y-m-d H:i:s");
        $order = new \AuctionCore\AuctionOrder\AuOrder($order_id);
        //找到订单对应的车辆所在地
        $area = $order->get_car_area($order_id);
        //找到对应分公司
        $branch_id = M('branch_city')->field('branch_id')->where(array('city_code'=>$area['location_area']))->find();
        //时间内对应分公司有没有对应活动
        $aid = $this->is_have_activity($nowdate,$branch_id['branch_id'],$type);
            // //找到活动对应分公司
            // $activity_info = $this->search_one($aid);
            // $company = new \AuctionCore\Other\Address();
            // $flag = false;
            // if ($activity_info['branch_id'] == 1) {
            //     //全国活动 不做限制
            //     $flag = true;
            // }else{
            //     //找到分公司下对应开展业务城市
            //     $citys = $company->get_city_by_companyid($activity_info['bc_city']);
            //     if ($citys) {
            //     $company_city = explode(',', $citys['city_code']);
            //     }
            //      //找到对应拍单对应车辆所在地
            //     $order = new \AuctionCore\AuctionOrder\AuOrder($order_id);
            //     $area = $order->get_car_area($order_id);
            //     $flag = in_array($area['location_area'], $company_city);
            // }
        if ($aid) {
            //查看对应活动拍单是否已经绑定奖券
            $is_lottery = $this->is_lottery($aid,$order_id);
            if (empty($is_lottery)) {
                  //找到活动下各种面值的奖券对应的数量 返回二维数组
                $arr_num = $this->get_denomination_type($aid);
                // $num = $this->not_gave_card_num($aid);
                //随机算法 得到一个随机面值
                $price = $this->get_rand_price($arr_num);
                //根据获取随机面额找到一条未分发卡券
                $redis = new \AuctionCore\Common\PhpRedis(0);
                //加锁 堵塞
                $key = getRedisKeyByCode('REDIS_KEY','100017');
                //$key = "order_binding_card";
                $redis->lock_wait($key);
                $cid = $this->get_one_card($price,$aid);
                if ($cid) {
                    //把这张卡券绑定订单
                    $ok = $this->binding($cid,$order_id);
                    $redis->unlock($key); 
                }else{
                    //该面值卡券已全部分发出去，递归需要重新去池子里面找
                    $redis->unlock($key);    
                    $newarr = array();
                    foreach ($arr_num as $k => $v) {
                        if ($v['price'] != $price) {
                            $newarr[] = $v;
                        }
                    }
                    if (count($newarr) < 1) {
                        return 0;
                    }
                    $ok = $this->again_search($newarr,$aid,$order_id);
                    $redis->unlock($key);
                }
            }
           
        }
        $res = array();
        $res['is_bool'] = $ok;
        $res['cid'] =$cid['cid']; 
        return  $res;
    }

    /**
     * 该面值卡券已全部分发出去，需要重新去池子里面找
     * @return  
     */
    private function again_search($arr,$aid,$order_id){
        $key = getRedisKeyByCode('REDIS_KEY','100017');
        //$key = "order_binding_card";
        $redis = new \AuctionCore\Common\PhpRedis(0);
        $price = $this->get_rand_price($arr);
        //根据获取随机面额找到一条未分发卡券
        $redis->lock_wait($key);
        $cid = $this->get_one_card($price,$aid);
        if ($cid) {
            //把这张卡券绑定订单
            $ok = $this->binding($cid,$order_id);
            $redis->unlock($key);
            return  $ok;
        }else{
            $redis->unlock($key);
            $newarr = array();
            foreach ($arr as $k1 => $v1) {
                if ($v1['price'] != $price) {
                    $newarr[] = $v1;
                }
            }
            if (count($newarr) < 1) {
                return 0;
            }
            return $this->again_search($newarr,$aid,$order_id);
            
        }
    }

    /**
     * 根据获取随机面试找到一条卡券
     * @return  array 卡券id
     */
    private function get_one_card($price,$aid){
        $where = array();
        $where['price'] = array('eq',$price);
        $where['order_id'] = array('eq',0);
        $where['a_id'] = array('eq',$aid);
        $one_card =  M('scratch_card')->field('cid')->where($where)->find();
        return $one_card;
    }

    /**
     * 获取指定活动下所有类型卡卷的数量
     * @return  array  
     */
    public function get_denomination_type($aid){
        $where['a_id'] = array('eq',$aid);
        return M('scratch_card')->field('count(*) as num,price')->where($where)->group('price')->order('price desc')->select();
    }


    /**
     * 获取指定活动下卡卷数量 余额 
     * @return  array 
     */
    public function get_num_balance($aid){
        $where['aid'] = array('eq',$aid);
        $map['a_id'] = array('eq',$aid);
        //活动总额
        $amount = M('activity')->field('amount')->where($where)->find();
        $denomination_num = M('scratch_card')->field('count(*) as num,price')->where($map)->group('price')->select();
        if (!empty($denomination_num)) {
            $denomination_num[0]['balance'] = $amount['amount'];
        }
        $newarr = array();
        foreach ($denomination_num as $key => $value) {
            $newarr[$key]['num'] = $value['num'];
            $newarr[$key]['price'] = $value['price'];
            if ($key == 0) {
                $newarr[$key]['balance'] = $value['balance'];
            }else{
                $newarr[$key]['balance'] = $newarr[$key-1]['balance'] - ($newarr[$key-1]['num']*$newarr[$key-1]['price']);
            }
        }
        return $newarr;
    }


    /**
    * 随机算法 有点恶心
    * @return  String 随机出来的面额
    **/
    private function get_rand_price($arr_num){
        //各种面额算出总数
        $allnum = 0;
        foreach ($arr_num as  $value) {
            $allnum += $value['num'];
        }
        $aaa = array();
        $all_num = '';
        $i = 0;
        foreach ($arr_num as  $v) {
            if ($i == 0) {
                //把面值高的概率调小一点
                //现在调整，代码不注释
                $aaa[$i]['a_num'] = ceil(($v['num']/$allnum)*1000000);
                $all_num += $aaa[$i]['a_num'];
            }else{
                $aaa[$i]['a_num'] = ceil(($v['num']/$allnum)*1000000);
                $all_num += $aaa[$i]['a_num'];
            }
            $aaa[$i]['price'] = $v['price'];
            $i++;
        }
        $bbb = array();
        //各种面额闭合区间
        foreach ($aaa as $k1 => $v1) {
            $bbb[$k1]['start_num'] = 1+$bbb[$k1-1]['end_num'];
            $bbb[$k1]['end_num'] = $v1['a_num'] + $bbb[$k1-1]['end_num'];
            $bbb[$k1]['price'] = $v1['price'];
        }
        //随机1-$all_num区间的数
        $id = mt_rand(1,$all_num);
        $type = "";
        foreach ($bbb as $k2 => $v2) {
            if ($id > $v2['start_num'] && $id < $v2['end_num']) {
                    return $v2['price'];
            }
        }
    }
    /**
     * 当前时间有没有对应活动类型的抽奖活动
     * @return  int 活动id
     */
    private function is_have_activity($nowdate,$branch_id,$type){
        $where = array();
        $where['starttime'] = array("elt",$nowdate);
        $where['endtime'] = array("egt",$nowdate);
        $where['branch_id'] = array("eq",$branch_id);
        $where['type'] = array('eq',$type);
        $aid = M('activity')->field('aid')->where($where)->order("createtime desc")->find();
        return $aid['aid'];
    }
    /**
     * 没有发放卡券数量
     * @return  
     */
    private function not_gave_card_num($aid){
        $where = array();
        $where['order_id'] = array('eq',0);
        $where['a_id'] = array('eq',$aid);
        $prefix = C('DB_PREFIX');
        $total = M('scratch_card')->where($where)->count();
        return $total;
    }

     /**
     *  给卡券绑定订单 
     * @return  int
     */
     private function binding($cid,$order_id){
        $ok = M('scratch_card')->where(array('cid'=>$cid['cid']))->save(array('order_id'=>$order_id));
        // echo M()->getlastsql();
        return $ok;
     }

     /**
     * 大转盘  卡券状态改成已刮开 state = 1 
     * @return  string 订单对应卡券的面额
     **/
     public function return_face_value($order_id){
        $one_card = M('scratch_card')->field('cid,price')->where(array('order_id'=>$order_id))->find();
        M('scratch_card')->where(array('cid'=>$one_card['cid']))->save(array('state'=>1,'adopttime'=>date("Y-m-d H:i:s")));
        return $one_card['price'];
     }

    /**
     * 修改卡券状态改成已使用 use_state = 1
     * @return  int 
     **/
     public function card_change_state($order_id){
        $one_card = M('scratch_card')->field('cid')->where(array('order_id'=>$order_id,'state'=>1))->find();
        $ok = 0;
        if ($one_card) {
             $ok = M('scratch_card')->where(array('cid'=>$one_card['cid']))->save(array('use_state'=>1));
        }
        return $ok;
     }

    /**
     *  获取卡券信息
     * @param $map array 条件
     * @return  array
     */
     public function find_cards($map){
        $card_info = M('scratch_card')->where($map)->select();
        return $card_info;
     }


    /**
     *  获取卡券 活动信息
     * @param $order_id $type $state 拍单id 活动类型 抽奖状态
     * @return  array
     */
     public function find_card_activity($order_id,$type,$state){
        $map = array();
        $map['c.order_id'] = $order_id;
        $map['a.type'] = $type;
        $map['c.state'] = $state;
        $prefix = C('DB_PREFIX');
        $card_info = M('scratch_card')->alias('c')->field("c.*,a.aid,a.a_name,a.type,a.starttime,a.endtime")
                ->join('left join '. $prefix."activity a  ON c.a_id = a.aid")
                ->where($map)->find();
        return $card_info;
     }

    /**
     *  获取活动表中的面值限制
     * @return   array
     */
    public function get_denomination($aid){
        $denomination = M('activity')->field('denomination')->where(array('aid'=>$aid))->find();
        return json_decode($denomination['denomination'],true);
    }


     //生成活动卡券
    public function create_card($aid,$num,$price){
        for ($i=1; $i <= $num ; $i++) {
            $data['a_id'] = $aid;
            $data['price'] = $price;
            $data['createtime'] = date('Y-m-d H:i:s');
            $id = M('scratch_card')->add($data);
            M('scratch_card')->where("cid='" . $id . "'")->save(array('card_no' => $id + 100000000));
        }
    }
    /**
    *
     */
    public function build_card($cards)
    {
        M()->startTrans();
        foreach ($cards as $index => $card) {
            $ok = M('build_card_log')->add($card);
            for ($i=1; $i <= $card['num'] ; $i++) {
                $data = [];
                $data['a_id'] = $card['aid'];
                $data['price'] = $card['denomination'];
                $data['createtime'] = date('Y-m-d H:i:s');
                $id = 0;
                $id = M('scratch_card')->add($data);
                if ($id > 0){
                    $ok2 = M('scratch_card')->where("cid='" . $id . "'")->save(array('card_no' => $id + 100000000));
                }
            }
        }
        if ($ok < 1 || $ok2 < 1)
        {
            M()->rollback();
            return false;
        }
        M()->commit();
        return true;
    }

    /**
     *  来拍车 获取正在进行中活动车商手机,卡券面额
     * @return   array
     */
    public function get_dealer_phone_card(){
        $map = array();
        $map['c.order_id'] = array('neq',0); 
        $map['c.state'] = array('eq',1); 
        $size = 20;
        $aid = $this->get_activity_id();
        $map['a.aid'] = array('eq',$aid);
        $cols = "c.price,cd.contact_mobile";
        $prefix = C('DB_PREFIX');
        $info = M('scratch_card')->alias('c')->field($cols)
            ->join($prefix."activity a  ON c.a_id = a.aid")
            ->join($prefix."order o ON o.order_id= c.order_id")
            ->join($prefix."car_dealer as cd ON cd.dealer_id = o.success_dealer_id")
            ->where($map)->limit($size)->order("c.adopttime desc")->select();
        return $info;
    }
    /**
     *  来拍车 找到一条正在进行中的活动id
     * @return   int 活动id
     */
    private function get_activity_id(){
        $nowdate = date('Y-m-d H:i:s');
        $where = array();
        $where['starttime'] = array('elt',$nowdate);
        $where['endtime'] = array('egt',$nowdate);
        $aid = M('activity')->field('aid')->where($where)->find();
        return $aid['aid'];
    }

    /**
    * 指定的活动下 某个拍单是否已经绑定奖券
    * @param $aid 活动id
    * @param $order_id
    * @return array 
    */
    private function is_lottery($aid,$order_id){
        $map = array();
        $map['a_id'] = array('eq',$aid);
        $map['order_id'] = array('eq',$order_id);
        $lottery = M('scratch_card')->where($map)->find();
        return $lottery;
    }

    /**
    * 发放奖券日志
    */
    public static function grant_lottery_log($data){
        $data['createtime'] = date('Y-m-d H:i:s');
        M('grant_lottery_log')->add($data);
    }

    /**
     * 追加活动金额
     */
    public function add_activity_amount($a_id,$amount)
    {
        $where = [];
        $where['aid'] = $a_id;
        return M('activity')->where($where)->setInc('amount',$amount);
    }
    /**
    * 获取生成奖券记录
     */
    public function get_build_card_log($aid)
    {
        $where = [];
        $where['c.aid'] = $aid;
        $cols = "a.amount,c.denomination,c.num,c.createtime";
        $prefix = C('DB_PREFIX');
        $build_card_log = [];
        $build_card_log = M('build_card_log')->alias('c')->field($cols)
                            ->join($prefix."activity a ON c.aid = a.aid")
                            ->where($where)->select();
        if (!empty($build_card_log)) {
            foreach ($build_card_log as $key => $value) {
                if (!isset($build_card_log[$key-1])) {
                    $build_card_log[$key]['surplus'] = $value['amount'];
                }else{
                    $build_card_log[$key]['surplus'] = $build_card_log[$key-1]['surplus'] -$build_card_log[$key-1]['denomination']*$build_card_log[$key-1]['num'];
                }
            }
        }
        // dump($build_card_log);
        return $build_card_log;
    }
}   

?>